set -e
[ -z "$DOMAIN" ] && {
    echo need DOMAIN=
    exit 1
}

[ -z "$1" ] && {
    echo "ss.sh server | client"
    exit 1
}

PORT="${PORT:-8830}"

TYPE="$1"

wget https://github.com/shadowsocks/shadowsocks-rust/releases/download/v1.20.1/shadowsocks-v1.20.1.x86_64-unknown-linux-musl.tar.xz -c -O ss.tar.xz
tar xf ss.tar.xz
mv ssserver sslocal /usr/local/bin/
rm -rf ssmanager  ssservice  ssurl

wget https://github.com/shadowsocks/v2ray-plugin/releases/download/v1.3.2/v2ray-plugin-linux-amd64-v1.3.2.tar.gz \
    -c -O v2ray-plugin-linux-amd64-v1.3.2.tar.gz
tar xf v2ray-plugin-linux-amd64-v1.3.2.tar.gz
mv v2ray-plugin_linux_amd64 /usr/local/bin/v2ray-plugin

cat <<EOF > /etc/systemd/system/ssserver.service
[Unit]
Description= server
After=syslog.target network.target remote-fs.target
[Service]
Restart=always
RestartSec=10
WorkingDirectory=/tmp
ExecStart=/usr/local/bin/ssserver -s [::]:8388 -m aes-256-gcm -k x49IuO --plugin v2ray-plugin --plugin-opts server;host=$DOMAIN
[Install]
WantedBy=multi-user.target
EOF

cat <<EOF > /etc/systemd/system/ssclient.service
[Unit]
Description= server
After=syslog.target network.target remote-fs.target
[Service]
Restart=always
RestartSec=10
WorkingDirectory=/tmp
ExecStart=/usr/local/bin/sslocal  -b "0.0.0.0:$PORT"  -s "$DOMAIN:443" -m "aes-256-gcm" -k "x49IuO" --plugin "v2ray-plugin" --plugin-opts "tls;host=$DOMAIN"
[Install]
WantedBy=multi-user.target

EOF

cat <<EOF 
server {
    listen       80;
    server_name  $DOMAIN;
    location / {
        proxy_pass http://127.0.0.1:8388;
        proxy_set_header Host $DOMAIN;
        proxy_set_header Upgrade $$http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}


  - name: o1s
    port: 443
    server: 129.150.37.91
    type: ss
    udp: true
    cipher: aes-256-gcm
    password: x49IuO
    plugin: v2ray-plugin
    plugin-opts:
      mode: websocket
      tls: true
      host: p2.doappz.org
    dialer-proxy: HK

sslocal -b "127.0.0.1:60080"  -s "p.doappz.org:443" -m "aes-256-gcm" -k "x49IuO" --plugin "v2ray-plugin" --plugin-opts "tls;host=p2.doappz.org"

EOF


if [ "$TYPE" = "server" ] ; then
    systemctl enable ssserver
    systemctl restart ssserver
else 
    systemctl enable ssclient
    systemctl restart ssclient
fi
